package cn.com.infcn.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import cn.com.infcn.po.Restful;
import cn.com.infcn.util.mss.MssClient;
import cn.com.infcn.util.mss.MssSearchApi;

/**
 * 搜索服務
 */
@Service
public class MssServiceImpl extends MssServiceI {

	@Value("${mss_ip}")
	private String mss_ip;
	@Value("${mss_port}")
	private int mss_port;
	@Value("${mss_timeout}")
	private int mss_timeout;
	@Value("${is_msp}")
	private boolean is_msp;//是否为msp搜索

	private MssClient mssClient;
	@Autowired
	private MssSearchApi mssSearchApi;

	private MssClient getMssClient() {
		if (mssClient == null) {
			synchronized (this) {
				if (mssClient==null) {
					if (is_msp) {
						mssClient=new MssClient(mss_ip, mss_port, mss_timeout, is_msp);  
					} else {
						mssClient = new MssClient(mssSearchApi);
					}
				}
			}
	
		}
		return mssClient;
	}


	@Override
	public JSONArray getFenleiForOne(String tableNames, String featchSize, int size, String query, String filter,
			String fields) {

		JSONArray returnJsonArray = new JSONArray();
		try {
			Restful response =  getMssClient().mssSearchApi_aggregationsByQuery(tableNames, featchSize, size,
					query, filter, fields);
			if (response.isOk()) {
				JSONObject jsonObj = response.getObj();
				JSONArray jsonArray = jsonObj.getJSONObject("aggregations").getJSONObject(fields)
						.getJSONArray("buckets");
				returnJsonArray = jsonArray;
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

		return returnJsonArray;
	}

	@Override
	public JSONArray getFenleiForTwo(String tableNames, String featchSize, int size, String query, String filter,
			String fields) {

		JSONArray returnJsonArray = new JSONArray();
		String[] split = fields.split(",");
		try {
			Restful response =  getMssClient().mssSearchApi_aggregationsByQuery(tableNames, featchSize, size,
					query, filter, fields);
			if (response != null && response.code()==200) {
					// System.out.println("失败==" + response.getContent());
				JSONObject jsonObj = response.getObj();
					JSONArray jsonArray = jsonObj.getJSONObject("aggregations")
							.getJSONObject(split[0]).getJSONArray("buckets");
					for (Object object : jsonArray) {
						JSONObject jSONObject2 = (JSONObject) object;
						JSONArray jsonArray2 = jSONObject2.getJSONObject(split[1]).getJSONArray("buckets");
						jSONObject2.remove(split[1]);
						jSONObject2.put("children", jsonArray2);
						returnJsonArray.add(jSONObject2);
					}
					returnJsonArray = jsonArray;
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

		return returnJsonArray;
	}

	@Override
	public JSONObject findOne(String tableNames, String defaultOperator, String query, String filter, String heighlight,
			String includes, String excludes, String sort) {
		// 处理开始索引

		int pageNum = 0;
		int size = 1;
		String distinct = "";
		findList(tableNames, pageNum, size, defaultOperator, query, filter, heighlight, includes, excludes, distinct,
				sort);
		JSONObject returnJSONObject = new JSONObject();
		try {
			Restful response =  getMssClient().mssSearchApi_searchByQuery(tableNames, 0, 1, defaultOperator,
					query, filter, heighlight, includes, excludes, "", sort);
			if (response != null && response.code()==200) {
					// System.out.println("失败==" + response.getContent());
					JSONObject jsonObj = response.getObj();
					JSONArray jsonArray = jsonObj.getJSONObject("hits").getJSONArray("hits");
					for (Object object : jsonArray) {
						JSONObject jSONObject = (JSONObject) object;
						JSONObject jsonObject_source = jSONObject.getJSONObject("_source");
						jsonObject_source.put("_id", jSONObject.getString("_id"));
						returnJSONObject = jsonObject_source;
						break;
					}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

		return returnJSONObject;
	}

	@Override
	public JSONObject findList(String tableNames, int pageNum, int size, String defaultOperator, String query,
			String filter, String heighlight, String includes, String excludes, String distinct, String sort) {

		// 处理开始索引
		int startIndex = 0;
		if (pageNum <= 0) {
			startIndex = 0;
		} else {
			startIndex = (pageNum - 1) * size;
		}
		// 处理最多能查询1万条数据的情况
		if (startIndex + size > 10000) {
			int server_Pages = (10000 + size) / size;
			startIndex = (server_Pages - 1) * size;
			size = 10000 - startIndex;
		}

		JSONObject returnJSONObject = new JSONObject();
		try {
			Restful response =  getMssClient().mssSearchApi_searchByQuery(tableNames, startIndex, size,
					defaultOperator, query, filter, heighlight, includes, excludes, distinct, sort);
			if (response != null && response.code()==200) {
					// System.out.println("失败==" + response.getContent());
					JSONArray returnRowsJsonArray = new JSONArray();

					JSONObject jsonObj = response.getObj();
					JSONArray jsonArray = jsonObj.getJSONObject("hits").getJSONArray("hits");
					Integer total = jsonObj.getJSONObject("hits").getInteger("total");
					for (Object object : jsonArray) {
						JSONObject jSONObject = (JSONObject) object;
						JSONObject jsonObject_source = jSONObject.getJSONObject("_source");
						jsonObject_source.put("_id", jSONObject.getString("_id"));
						returnRowsJsonArray.add(jsonObject_source);
					}

					returnJSONObject.put("total", total > 10000 ? 10000 : total);
					returnJSONObject.put("total_real", total);
					returnJSONObject.put("rows", returnRowsJsonArray);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

		return returnJSONObject;
	}

	@Override
	public JSONArray findAll(String tableNames, String query, String filter, String sort) {
		JSONArray returnJSONArray = new JSONArray();
		try {
			Restful response =  getMssClient().mssSearchApi_searchByQuery(tableNames, 0, 10000, "OR", query,
					filter, "", "", "", "", sort);
			if (response != null && response.code()==200) {
					// System.out.println("失败==" + response.getContent());
					JSONArray returnRowsJsonArray = new JSONArray();
					JSONObject jsonObj = response.getObj();
					JSONArray jsonArray = jsonObj.getJSONObject("hits").getJSONArray("hits");
					for (Object object : jsonArray) {
						JSONObject jSONObject = (JSONObject) object;
						JSONObject jsonObject_source = jSONObject.getJSONObject("_source");
						jsonObject_source.put("_id", jSONObject.getString("_id"));
						returnRowsJsonArray.add(jsonObject_source);
					}

					returnJSONArray = returnRowsJsonArray;
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

		return returnJSONArray;
	}
}
